package com.example.dish.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.example.common.Result;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${take_out.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        log.info(file.toString());
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //获取最后一个点的位置,开始截取,拿到后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID随机生成一个UUID文件名,再拼接后缀名
        String fileName = UUID.randomUUID() + suffix;
        File dir = new File(basePath);

        //如果转存路径不存在,就创建它
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定路径
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(fileName);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info("name:{}", name);
        log.info("basepath:{}", basePath);
        try {
            //通过输入流,读取数据
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //因为是要回显到浏览器,所以输出流调用的是response的
            ServletOutputStream outputStream = response.getOutputStream();
            //定义字节数组
            int len = 0;
            byte[] bytes = new byte[1024];
            //循环读取数据,用输出流写到浏览器上进行回显
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //释放流
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteImg(String imgPath) {
        File file = new File(basePath + imgPath);
        if (file.delete()) {
            log.info("成功删除路径:{}下的图片",file.getPath());
        } else {
            log.info("路径:{}下的图片删除失败",file.getPath());
        }
    }
}
